package com.yjhb.android.sbz.fragment;

import android.content.Intent;
import android.graphics.Typeface;
import android.os.CountDownTimer;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.ViewSwitcher;

import androidx.coordinatorlayout.widget.CoordinatorLayout;

import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.tabs.TabLayout;
import com.yjhb.android.sbz.App;
import com.yjhb.android.sbz.R;
import com.yjhb.android.sbz.activity.EverydayWelfareActivity;
import com.yjhb.android.sbz.activity.MyTaskActivity;
import com.yjhb.android.sbz.activity.PublishTypeActivity;
import com.yjhb.android.sbz.activity.SearchActivity;
import com.yjhb.android.sbz.adapter.TaskListItemAdapter;
import com.yjhb.android.sbz.entity.Label;
import com.yjhb.android.sbz.entity.TaskInfo;
import com.yjhb.android.sbz.manager.ResManager;
import com.yjhb.android.sbz.mvp.hall.HallPresenter;
import com.yjhb.android.sbz.mvp.hall.HallTaskView;
import com.yjhb.android.sbz.popup.TypePopup;
import com.yjhb.android.sbz.tool.AnimationTool;
import com.yjhb.android.sbz.tool.EventMsg;
import com.yjhb.android.sbz.tool.LoadingDialogTool;
import com.yjhb.android.sbz.tool.Tool;
import com.jojo.android.zxlib.base.BaseFragment;
import com.jojo.android.zxlib.base.BaseRecyclerAdapter;
import com.jojo.android.zxlib.tool.Global;
import com.jojo.android.zxlib.tool.ZxActivityTool;
import com.jojo.android.zxlib.tool.ZxLogTool;
import com.jojo.android.zxlib.tool.ZxToast;
import com.jojo.android.zxlib.tool.ZxTool;
import com.jojo.android.zxlib.view.EmptyRecyclerView;
import com.jojo.android.zxlib.view.dialog.ILoading;
import com.qmuiteam.qmui.widget.QMUITabSegment;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.tencent.qcloud.tim.uikit.Observer;
import com.tencent.qcloud.tim.uikit.UnReadManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 创建者 zx
 * 创建时间 2020/11/18 11:35
 */
public class HallFragment extends BaseFragment<HallPresenter> implements View.OnTouchListener, TabLayout.BaseOnTabSelectedListener, OnRefreshLoadmoreListener, QMUITabSegment.OnTabSelectedListener, PopupWindow.OnDismissListener, TypePopup.onSelectedLabelListener, BaseRecyclerAdapter.ItemClickListener<TaskInfo>, HallTaskView, Observer<Integer> {
    private final String TAG = "HallFragment";

    @BindView(R.id.rootContainer)
    CoordinatorLayout rootContainer;
    @BindView(R.id.appBarLayout)
    AppBarLayout appBarLayout;
    @BindView(R.id.viewSwitcher)
    ViewSwitcher viewSwitcher;
    @BindView(R.id.tabLayout)
    TabLayout tabLayout;
    @BindView(R.id.recommend_title_tv)
    TextView recommend_title_tv;
    @BindView(R.id.countdown_time_tv)
    TextView countdown_time_tv;
    @BindView(R.id.countdown_time)
    View countdown_time;

    @BindView(R.id.recyclerView)
    EmptyRecyclerView recyclerView;
    @BindView(R.id.smartRefreshLayout)
    SmartRefreshLayout smartRefreshLayout;
    @BindView(R.id.layout_empty)
    View empty_layout;
    @BindView(R.id.sort_tabLayout)
    QMUITabSegment sort_tabLayout;
    @BindView(R.id.type_tv)
    TextView type_tv;
    @BindView(R.id.filterView)
    View filterView;
    @BindView(R.id.title_layout)
    View title_layout;
    @BindView(R.id.unread_tv)
    TextView unreadTv;
    @BindView(R.id.msgView)
    FrameLayout msgView;
    @BindView(R.id.tips_tv)
    TextView tips_tv;

    private ILoading loadingDialog;
    private CountDownTimer countDownTimer;


    //顶部广告位的任务
    private List<TaskInfo> adTasks;
    //大厅悬赏列表的任务
    private List<TaskInfo> tasks = new ArrayList<>();
    //大厅列表适配器
    private TaskListItemAdapter adapter;
    //标签集合
    private List<Label> labels = new ArrayList<>();
    //标签弹窗
    private TypePopup typePopup = null;
    //页面大小
    private final int size = 25;
    //当前页面
    private int current = 1;
    //排序方式  1.综合 2.最新 3.简单 4.高价 5.未做
    private int sort = 1;
    //分类id  null= all
    private Integer categoryId = null;
    //类型   null全部 1简单 2高价
//    private Integer type = null;

    //推荐广告滚动计时器
    private Timer timer;
    //推荐广告索引
    private int adIndex;
    //是否正在加载中
    private boolean isLoading;


    @Override
    protected HallPresenter initPresenter() {
        return new HallPresenter(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_hall;
    }

    @Override
    protected void initUI() {
        recommend_title_tv.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD_ITALIC));
        //初始化广告位
        initAd();
        //滚动广告位
        adRoll();
        //初始化一级分类：全部、简单、高价
        initTabLayout();
        //初始化二级排序分类：综合、人气、最新、价格
        initTabLayoutSort();
        //初始化recyclerView部分
        initRecyclerView();
        //初始化标签部分
        initLabel(sort);
        //创建标签弹窗
        typePopup = new TypePopup(getContext(), labels);
        //每日专享计时器
        countdownTime();
        loadingDialog = LoadingDialogTool.createDialog(this);
    }


    private void initLabel(int sort) {
        String s = null;

        labels.clear();
        Label label = new Label();
        label.setTitle("全部");
        label.setTag(null);
        labels.add(label);

        //如果type==null 或者type == 2 则显示高价标签
        if (sort == 1 || sort == 2 || sort == 4 || sort == 5) {
            label = new Label();
            label.setTitle(s = getString(R.string.task_type_download_app));
            label.setTag(Tool.publishTypeTransformID(s));
            labels.add(label);


            label = new Label();
            label.setTitle(s = getString(R.string.task_type_approve));
            label.setTag(Tool.publishTypeTransformID(s));
            labels.add(label);


            label = new Label();
            label.setTitle(s = getString(R.string.task_type_eCommerce));
            label.setTag(Tool.publishTypeTransformID(s));
            labels.add(label);

            label = new Label();
            label.setTitle(s = getString(R.string.task_type_app_apply));
            label.setTag(Tool.publishTypeTransformID(s));
            labels.add(label);

        }
        //如果type==null 或者type == 1 则显示简单标签
        if (sort == 1 || sort == 2 || sort == 3 || sort == 5) {
            label = new Label();
            label.setTitle(s = getString(R.string.task_type_bargain_help));
            label.setTag(Tool.publishTypeTransformID(s));
            labels.add(label);


            label = new Label();
            label.setTitle(s = getString(R.string.task_type_follow_vote));
            label.setTag(Tool.publishTypeTransformID(s));
            labels.add(label);


            label = new Label();
            label.setTitle(s = getString(R.string.task_type_forward));
            label.setTag(Tool.publishTypeTransformID(s));
            labels.add(label);

            label = new Label();
            label.setTitle(s = getString(R.string.task_type_register));
            label.setTag(Tool.publishTypeTransformID(s));
            labels.add(label);
        }
        //如果type==null 则显示其他标签
        if (sort == 1 || sort == 2 || sort == 5) {
            label = new Label();
            label.setTitle(s = getString(R.string.task_type_other));
            label.setTag(Tool.publishTypeTransformID(s));
            labels.add(label);
        }
        if (typePopup != null)
            typePopup.refresh();
    }

    private void initRecyclerView() {
        recyclerView.setEmptyView(empty_layout);
        recyclerView.setAdapter(adapter = new TaskListItemAdapter(getContext()));
        adapter.setData(tasks);
    }

    private void initTabLayoutSort() {
        sort_tabLayout.setDefaultSelectedColor(getResources().getColor(R.color.red_31));
        sort_tabLayout.setDefaultNormalColor(getResources().getColor(R.color.gray_66));
        sort_tabLayout.setTabTextSize(ZxTool.dip2px(14));
        sort_tabLayout.setIndicatorWidthAdjustContent(false);
        sort_tabLayout.addTab(new QMUITabSegment.Tab("综合"));
        sort_tabLayout.addTab(new QMUITabSegment.Tab("最新"));
        sort_tabLayout.addTab(new QMUITabSegment.Tab("简单"));
        sort_tabLayout.addTab(new QMUITabSegment.Tab("高价"));
        sort_tabLayout.addTab(new QMUITabSegment.Tab("未做"));
//        sort_tabLayout.addTab(new QMUITabSegment.Tab("价格"));
        sort_tabLayout.selectTab(0);
    }


    @Override
    protected void initEvent() {
        tabLayout.addOnTabSelectedListener(this);
        countdown_time.setOnTouchListener(this);
        EventBus.getDefault().register(this);
        UnReadManager.getInstance().register(this);
        smartRefreshLayout.setOnRefreshLoadmoreListener(this);
        sort_tabLayout.addOnTabSelectedListener(this);
        typePopup.setOnDismissListener(this);
        typePopup.setOnSelectedLabelListener(this);
        adapter.setOnItemClick(this);
        msgView.setOnClickListener(v -> {
            if (Tool.checkLogin(getContext())) {
                ZxActivityTool.skipActivity(getContext(), MyTaskActivity.class);
                UnReadManager.getInstance().setUnreadTask(0);
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMsg(EventMsg msg) {
        if (msg.msg == EventMsg.REQUEST_HALL_SWITCH_LOW) {
            tabLayout.getTabAt(1).select();
        } else if (msg.msg == EventMsg.REQUEST_HALL_SWITCH_HIGH) {
            tabLayout.getTabAt(2).select();
        } else if (msg.msg == EventMsg.HALL_TOP_REFRESH) {
            CoordinatorLayout.Behavior behavior =
                    ((CoordinatorLayout.LayoutParams) appBarLayout.getLayoutParams()).getBehavior();
            if (behavior instanceof AppBarLayout.Behavior) {
                AppBarLayout.Behavior appBarLayoutBehavior = (AppBarLayout.Behavior) behavior;
                int topAndBottomOffset = appBarLayoutBehavior.getTopAndBottomOffset();
                if (topAndBottomOffset != 0) {
                    appBarLayoutBehavior.setTopAndBottomOffset(0);
                }
            }
            request(true, true);
        }
    }

    @Override
    public void onUserVisibleChanged(boolean visible) {
        super.onUserVisibleChanged(visible);
        if (visible) {
            try {
                //当悬赏大厅重新可见时，重置数据
                categoryId = null;
                sort = 1;
                tabLayout.getTabAt(0).select();
                sort_tabLayout.selectTab(0);
                presenter.randomHomePageList();
                request(true, true);
            } catch (Exception e) {
                ZxLogTool.err(e);
            }

        }
    }

    @Override
    protected void initData() {
        presenter.randomHomePageList();
        request(true, true);
    }


    private void countdownTime() {
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        calendar.add(Calendar.DAY_OF_MONTH, 1);
        long currTime = System.currentTimeMillis();
        long time = calendar.getTimeInMillis() - currTime;
        countDownTimer = new CountDownTimer(time, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                int hour = (int) (millisUntilFinished / 1000 / 60 / 60);
                int min = (int) ((millisUntilFinished - (hour * 1000 * 60 * 60)) / 1000 / 60);
                int second = (int) ((millisUntilFinished - (hour * 1000 * 60 * 60) - (min * 1000 * 60)) / 1000);
                String countdownTime = new StringBuilder()
                        .append(hour < 10 ? "0" + hour : hour)
                        .append(":")
                        .append(min < 10 ? "0" + min : min)
                        .append(":")
                        .append(second < 10 ? "0" + second : second)
                        .toString();
                countdown_time_tv.setText(countdownTime);
            }

            @Override
            public void onFinish() {
                countdownTime();
            }
        };
        countDownTimer.start();
    }


    /**
     * 初始化tab
     */
    private void initTabLayout() {
        tabLayout.addTab(tabLayout.newTab());
        tabLayout.addTab(tabLayout.newTab());
        tabLayout.addTab(tabLayout.newTab());
        tabLayout.getTabAt(0).setText("全部").setTag("0");
        tabLayout.getTabAt(1).setText("简单").setTag("1");
        tabLayout.getTabAt(2).setText("高价").setTag("2");
    }


    /**
     * 初始化广告位推荐
     */
    private void initAd() {
        viewSwitcher.setInAnimation(AnimationTool.getInAnim());
        viewSwitcher.setOutAnimation(AnimationTool.getOutAnim());
    }


    boolean isMove;
    float srcX, srcY;

    /**
     * 拖动计时器
     *
     * @param v
     * @param event
     * @return
     */
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            srcX = event.getRawX();
            srcY = event.getRawY();
        }
        if (event.getAction() == MotionEvent.ACTION_MOVE) {
            ZxLogTool.i("移动中 X:" + Math.abs(event.getRawX() - srcX) + "  Y:" + Math.abs(event.getRawY() - srcY));
            if (Math.abs(event.getRawX() - srcX) > 10 || Math.abs(event.getRawY() - srcY) > 10) {
                isMove = true;
                v.setX(v.getX() + event.getX() - v.getWidth() / 2);
                v.setY(v.getY() + event.getY() - v.getHeight() / 2);
            }
        }
        if (event.getAction() == MotionEvent.ACTION_CANCEL || event.getAction() == MotionEvent.ACTION_UP) {
            ZxLogTool.i("抬起手指");
            if (isMove) {
                ZxLogTool.i("移动后抬起手指");
                isMove = false;
                return true;
            }
        }
        return false;
    }

    @OnClick(R.id.publish_ll)
    void publish_ll() {
        if (Tool.checkLogin(getContext())) {
            startActivity(new Intent(getContext(), PublishTypeActivity.class));
        }
    }

    @OnClick(R.id.search_tv)
    void search_tv() {
        if (Tool.checkLogin(getContext())) {
            if (App.userInfo == null || App.userInfo.getScore() < 30) {
                ZxToast.showINFOBottomToast("信誉积分不小于30就可以使用了哦！");
                return;
            }
            ZxActivityTool.skipActivity(getContext(), SearchActivity.class);
        }

    }

    @OnClick(R.id.countdown_time)
    void countdown_time() {
        ZxActivityTool.skipActivity(getContext(), EverydayWelfareActivity.class);

    }

    /**
     * 广告位推荐滚动
     */
    public void adRoll() {
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Global.getInstance().getMainHandler().post(new Runnable() {
                    @Override
                    public void run() {
                        if (viewSwitcher != null) {
                            final View t = viewSwitcher.getNextView();
                            LinearLayout linearLayout = (LinearLayout) t;
                            TextView titleTv = (TextView) linearLayout.getChildAt(0);
                            TextView moneyTv = (TextView) linearLayout.getChildAt(1);
                            if (adTasks != null && adTasks.size() > 0) {
                                if (adIndex < adTasks.size() - 1) {
                                    adIndex++;
                                    if (adIndex == adTasks.size()) {
                                        presenter.randomHomePageList();
                                    }
                                } else {
                                    adIndex = 0;
                                }
                                titleTv.setText(adTasks.get(adIndex).getTitle());
                                moneyTv.setText("+" + adTasks.get(adIndex).getMoney() + "元");
                                viewSwitcher.showNext();
                            } else {
                                titleTv.setText("");
                                moneyTv.setText("");
                                viewSwitcher.showNext();
                            }
                        }
                    }
                });
            }
        }, 5000, 5000);
    }

    @OnClick(R.id.viewSwitcher)
    void textSwitcher() {
        if (adTasks != null && adIndex < adTasks.size())
            Tool.startEditTaskDetailActivity(getContext(), adTasks.get(adIndex).getId());
    }

    @OnClick(R.id.type_tv)
    void type_tv(TextView view) {
        view.setSelected(!view.isSelected());
        if (view.isSelected()) {
            showTypePopup();
            view.setTextColor(ResManager.getThemeColor());
            view.getCompoundDrawables()[2].setTint(ResManager.getThemeColor());
            EventBus.getDefault().post(new EventMsg(EventMsg.DISPLAY_BOTTOM_MASK, null));
            filterView.setVisibility(View.VISIBLE);
        } else {
            view.setTextColor(getResources().getColor(R.color.gray_66));
            view.getCompoundDrawables()[2].setTint(getResources().getColor(R.color.gray_66));
            EventBus.getDefault().post(new EventMsg(EventMsg.HIDE_BOTTOM_MASK, null));
            filterView.setVisibility(View.GONE);
        }
    }

    private void showTypePopup() {
        typePopup.showAsDropDown(title_layout);
    }


    @Override
    public void onDestroy() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (countDownTimer != null) {
            countDownTimer.cancel();
            countDownTimer = null;
        }
        UnReadManager.getInstance().unregister(this);
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    public void request(boolean showLoading) {
        request(showLoading, false);
    }

    public void request(boolean showLoading, boolean refresh) {
        if (showLoading)
            if (loadingDialog != null)
                loadingDialog.show();
        if (refresh) {
            current = 1;
            categoryId = null;
            if (typePopup != null)
                typePopup.selectedFirst();
        }
        if (presenter != null)
            presenter.loadHallListV2(sort, categoryId, size, current);

    }


    @Override
    public void onListData(List<TaskInfo> tasks, boolean isRefresh) {
        loadingDialog.cancel();
        if (smartRefreshLayout != null) {
            smartRefreshLayout.finishLoadmore();
            smartRefreshLayout.finishRefresh();
        }
        if (isRefresh) {
            this.tasks.clear();
        } else {
            if ((tasks == null || tasks.size() == 0) && this.tasks != null) {
                current = 1;
                List<TaskInfo> taskInfos = new ArrayList<>();
                for (TaskInfo taskInfo : this.tasks) {
                    taskInfos.add(taskInfo);
                    if (taskInfos.size() >= 15) {
                        break;
                    }
                }
                tasks = taskInfos;
            }
        }
        this.tasks.addAll(tasks);
        adapter.notifyDataSetChanged();
        if (isRefresh) {
            recyclerView.scrollToPosition(0);
        }
    }

    /**
     * 顶部广告回调
     *
     * @param tasks
     */
    @Override
    public void onRandomList(List<TaskInfo> tasks) {
        this.adTasks = tasks;
        adIndex = 0;
    }

    /**
     * 失败回调
     *
     * @param code
     * @param msg
     */
    @Override
    public void onFailure(int code, String msg) {
        if (smartRefreshLayout != null) {
            smartRefreshLayout.finishRefresh();
            smartRefreshLayout.finishLoadmore();
        }
        if (loadingDialog != null)
            loadingDialog.cancel();
        ZxToast.showINFOBottomToast(msg);
    }

    @Override
    public void onTabSelected(TabLayout.Tab tab) {

    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {

    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {

    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        current++;
        request(false);
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        current = 1;
        request(false);
    }


    @Override
    public void onTabSelected(int index) {
        tips_tv.setVisibility(index == 4?View.VISIBLE:View.GONE);
        sort = index + 1;
        initLabel(sort);
        request(true, true);
    }

    @Override
    public void onTabUnselected(int index) {

    }

    @Override
    public void onTabReselected(int index) {

    }

    @Override
    public void onDoubleTap(int index) {

    }

    @Override
    public void onDismiss() {
        type_tv(type_tv);
    }

    @Override
    public void onSelectedLabel(Label label) {

    }

    @Override
    public void onClickSelectedLabel(Label label) {
        categoryId = (Integer) label.getTag();
        request(true, false);
        typePopup.dismiss();
    }

    @Override
    public void onItemClick(int index, TaskInfo taskInfo) {
        Tool.startEditTaskDetailActivity(getContext(), taskInfo.getId());
    }

    @Override
    public void onViewClick(View view, String msg, int index, TaskInfo taskInfo) {

    }

    @Override
    public void update(int type, Integer arg) {
        int totalUnread = UnReadManager.getInstance().getUnreadTask();
        if (totalUnread > 0) {
            msgView.setVisibility(View.VISIBLE);
            unreadTv.setVisibility(View.GONE);
            unreadTv.setText(String.valueOf(totalUnread));
        } else {
            msgView.setVisibility(View.VISIBLE);
            unreadTv.setVisibility(View.GONE);
            unreadTv.setText("");
        }
    }
}
